package com.mycompany.xxy_dome.view;
import com.mycompany.xxy_dome.controller.LoginController;
import com.mycompany.xxy_dome.modle.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginGUI extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;

    public LoginGUI() {
        // 设置窗口标题
        setTitle("登录界面");
        // 设置窗口大小
        setSize(350, 200);
        // 设置窗口关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口居中显示
        setLocationRelativeTo(null);
        // 设置窗口大小不可变
        setResizable(false);

        // 使用BorderLayout作为顶层布局
        setLayout(new BorderLayout());

        // 创建一个面板用于放置表单元素
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        formPanel.setBackground(Color.WHITE);  // 设置背景色

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);  // 设置内边距
        gbc.anchor = GridBagConstraints.WEST;  // 左对齐
        gbc.fill = GridBagConstraints.HORIZONTAL;  // 水平填充

        // 添加用户名标签和文本框
        JLabel userLabel = new JLabel("用户名:");
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(userLabel, gbc);

        usernameField = new JTextField(20);
        gbc.gridx = 1;
        gbc.gridy = 0;
        formPanel.add(usernameField, gbc);

        // 添加密码标签和密码框
        JLabel passLabel = new JLabel("密码:");
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(passLabel, gbc);

        passwordField = new JPasswordField(20);
        gbc.gridx = 1;
        gbc.gridy = 1;
        formPanel.add(passwordField, gbc);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBackground(Color.WHITE);  // 设置背景色

        // 创建登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());
                LoginController loginController = new LoginController();
                if (!loginController.Controller(username, password)) {
                    JOptionPane.showMessageDialog(LoginGUI.this, "用户名或密码不正确", "登录失败", JOptionPane.ERROR_MESSAGE);
                }
                else {
                    setVisible(false);
                }
            }
        });
        buttonPanel.add(loginButton);

        // 添加组件到主窗口
        add(formPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 设置窗口可见
        setVisible(true);
    }

}


